<?php
	use\ampleharvest\code;
	use\ampleharvest\code\cConfig;

	require_once dirname(dirname(dirname(dirname(__FILE__)))) . '/config/cConfig.php';
	require_once 'cSolr.php';


	class cFacets
	{
		private $m_obj_Solr = null;
		private $m_str_Prefix = "";
		private $m_str_BaseQuery = "*:*";
		private $m_str_Facet = "";

		private $m_arr_Errors = array();
		
	    function __construct($type)
		{
			if(strcmp ($type, "PROCUREMENTS") == 0)
			{
				$this->m_obj_Solr = new cSolr(cConfig::C_STR_SOLR_HOST_GE, cConfig::C_INT_SOLR_PORT_GE, cConfig::C_STR_SOLR_SVR_PATH_GE);
			}
			else if(strcmp ($type, "ARTICLES") == 0)
			{
				$this->m_obj_Solr = new cSolr(cConfig::C_STR_SOLR_HOST_OS, cConfig::C_INT_SOLR_PORT_OS, cConfig::C_STR_SOLR_SVR_PATH_OS);
			}
			else 
			{
			    $this->m_obj_Solr = new cSolr(null, null, null);
			}
		}

		public function set_Prefix($str_Prefix)
		{
			$this->m_str_Prefix = $str_Prefix;
		}

		public function set_Facet($str_Facet)
		{
			$this->m_str_Facet = $str_Facet;
		}

		public function set_BaseQuery($str_BaseQuery)
		{
			$this->m_str_BaseQuery = $str_BaseQuery;
		}

		protected function add_Error($str_Msg)
		{
			$this->m_arr_Errors[] = $str_Msg;
		}

		public function get_LastError()
		{
			$int_Size = sizeof($this->m_arr_Errors);
			if ($int_Size < 1)
			{
				return "No Errors";
			}
			return $this->m_arr_Errors[$int_Size];
		}

		public function get_AllErrors()
		{
			return $this->m_arr_Errors;
		}

		public function get_OutputArray()
		{
			$arr_Output = array();
			if (!$this->m_str_Facet)
			{
				$this->add_Error("You have not specified a Facet to search for.");
				return false;
			}

			$obj_Response = $this->m_obj_Solr->search($this->m_str_BaseQuery,
				0,
				0,
				array(
				"rows"			 => 0,
				"facet.field"	 => $this->m_str_Facet,
				"facet.mincount" => 1,
				"facet.prefix"	 => $this->m_str_Prefix,
				"facet"			 => "on",
				"facet.limit"	 => 1000
			));

			if ($obj_Response->getHttpStatus() == 200)
			{
				if (@$obj_Response->facet_counts)
				{
					foreach ($obj_Response->facet_counts->facet_fields as $str_Field)
					{
						foreach ($str_Field as $str_Term => $int_Count)
						{
							$arr_Temp = array();
							if (is_numeric($str_Term))
							{
								$arr_Temp["term"] = (float) $str_Term;
							}
							else
							{
								$arr_Temp["term"] = $str_Term;
							}
							$arr_Temp["count"] = $int_Count;
							$arr_Temp["label"] = $str_Term . " ($int_Count)";
							$arr_Output[] = $arr_Temp;

						}
					}
				}
			}
			else
			{
				$this->add_Error($obj_Response->getHttpStatusMessage());
				return false;
			}
			return $arr_Output;
		}

	}
?>